/**
  ******************************************************************************
  * @file    DPC_IRQ_Handlers.c
  * @author  STMicroelectronics
  * @version 1.0.0
  * @date    06-Jun-2022
  * @brief   Interrupt Service Routines
  * @details This application example is a Buck PSU converter
  ******************************************************************************
  *
  * Copyright (c) 2019 Biricha Digital Power Limited
  * Copyright (c) 2021(-2022) STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file in
  * the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  ******************************************************************************
  */
/** @addtogroup STM32_DPOW
  * @brief  Digital Power application implemented with a STM32 MCU
  * @{
  */

/** @addtogroup PSU_IRQ_HANDLER
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32g4xx_it.h"
#include "dpwr.h"
#include "app_X-CUBE-DPower.h"
#include "DPC_Lib_Conf.h"
#include "DCDC_Globals.h"
#include "DPC_STM32_Interface.h"
#ifdef PLOT_WAVEFORM
#include "DPC_DebugMode.h"
#endif
#include "DPC_Miscellaneous.h"
#include "DPC_Pid.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
int32_t Vout;
int32_t CompareReg;

/* Private function prototypes -----------------------------------------------*/
/* External variables --------------------------------------------------------*/
#ifdef PLOT_WAVEFORM
extern WAVEFORM_DISPLAY_INFO_t Waveform;
#endif

/* External functions ---------------------------------------------------------*/
/******************************************************************************/
/*           Cortex-M4 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/**
  * @brief This function handles System tick timer.
  */
void SysTick_Handler(void)
{
  HAL_IncTick();

  if (hDCDC_StartUp_TimeLeft !=0) hDCDC_StartUp_TimeLeft--;
  if (hDCDC_Wait_TimeLeft !=0) hDCDC_Wait_TimeLeft--;
  #if (SHORT_CIRCUIT_PROTECTION == true)
  if (hDCDC_UndervoltageValidation_TimeLeft != 0) hDCDC_UndervoltageValidation_TimeLeft--;
  #endif

  LED_DecreaseBlinkCounter(&LED_GREEN_Status);
  LED_DecreaseBlinkCounter(&LED_RED_Status);
  LED_DecreaseBlinkCounter(&LED_BLUE_Status);
  LED_DecreaseBlinkCounter(&LED_ORANGE_Status);

  /* Update soft start direction */
  CNTRL_RampSetDirection( &myDcdc.vRamp, bPowerUp );

  /* Soft start/stop update */
  CNTRL_RampUpdate(&myDcdc.vRamp);
  vLoop.m_Ref = myDcdc.vRamp.m_Out;

  #ifdef PLOT_WAVEFORM
  // Play back data captured during ISR
  WaveFormDisplay(&Vout, &CompareReg);
  #endif
}

/**
  * @brief  EXTI line detection callback.
  * @param  GPIO_Pin: Specifies the port pin connected to corresponding EXTI line.
  * @retval None
  */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
  /* JOYSTICK UP enables automatic load transients toggling */
  if (GPIO_Pin == JOYSTICK_UP_Pin)
  {
    /* Set Blue LED ON */
    LED_SetParams(&LED_BLUE_Status, LED_ON, 0, 0, 0);
  }

  /* JOYSTICK DOWN disables automatic load transients toggling */
  if (GPIO_Pin == JOYSTICK_DOWN_Pin)
  {
    /* Set Blue LED OFF */
    LED_SetParams(&LED_BLUE_Status, LED_OFF, 0, 0, 0);
  }

  /* JOYSTICK RIGHT increases the activated Resistors load */
  if (GPIO_Pin == JOYSTICK_RIGHT_Pin)
  {
    /* Clamp the value to Max if over-pressed by user */
    if (Demo.NbrActiveLoad < 2)
    {
      Demo.NbrActiveLoad += 1;
      #ifdef PLOT_WAVEFORM
      WaveFormTrigger();
      #endif
    }
  }

  /* JOYSTICK LEFT decreases the activated Resistors load */
  if (GPIO_Pin == JOYSTICK_LEFT_Pin)
  {
    /* Clamp the value to Min if over-pressed by user */
    if (Demo.NbrActiveLoad > 0)
    {
      Demo.NbrActiveLoad -= 1;
      #ifdef PLOT_WAVEFORM
      WaveFormTrigger();
      #endif
    }
  }

  /* Set Orange LED blinking depending on How many loads are activated */
  LED_SetParams(&LED_ORANGE_Status, LED_BLINK_N, Demo.NbrActiveLoad, (uint16_t)(LED_BLINK_PERIOD_SHORT_MS/Demo.NbrActiveLoad) , 10000);

  /* Handle the load appropriately to user's expectation */
  LoadHandler();
}

/******************************************************************************/
/* Dedicated STM32G4xx Peripheral Interrupt Handlers                          */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file.                                          */
/******************************************************************************/

/******************************************************************************/
/* Common STM32F3xx & STM32G4xx Peripheral Interrupt Handlers                 */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file.                                          */
/******************************************************************************/
/**
  * @brief This function handles ADC1 and ADC2 interrupts.
  * @param  None
  * @retval None
  */
void ADC1_2_IRQHandler(void)
{
  /* Set GPO1 to high for timing purposes */
  __HAL_GPIO_SET_PIN(DEBUG_PORT, DEBUG_PIN);

  /* Clear ADC interrupt flag */
  __HAL_ADC_CLEAR_FLAG( &DPC_APPL_ADCx, ADC_FLAG_EOS );

  /* Get conversion value of Vin */
//  vLoop.m_Fdbk = __HAL_ADC1_GET_VALUE();
  vLoop.m_Fdbk = LL_ADC_REG_ReadConversionData12(((&DPC_APPL_ADCx)->Instance));

  /* Run 3p3z controller */
  CNTRL_3p3z(&vLoop);

  /* Update PWM compare register to new duty cycle */
  __HAL_HRTIM_SETCOMPARE( &DPC_APPL_HRTIM, HRTIM_TIMERINDEX_TIMER_C, HRTIM_COMPAREUNIT_1, (uint32_t)vLoop.m_Out );

  #ifdef PLOT_WAVEFORM
  /* Recording ADC value and controller output for replay via debug */
  if (Waveform.m_State == WAVEFORM_RECORD)
  {
    WaveFormRecord((uint16_t)vLoop.m_Fdbk, (uint16_t)vLoop.m_Out);
  }
  #endif

  /* Set GPO1 to low for timing purposes */
  __HAL_GPIO_RESET_PIN(DEBUG_PORT, DEBUG_PIN);
}

/**
  * @} end PSU_IRQ_HANDLER
  */

/**
  * @}  end STM32_DPOW
  */
